/*
 * @FilePath: /flutter_cart/lib/provide/category_goods_list.dart
 * @Author: Yongchao Wang
 * @Date: 2020-12-05 08:03:19
 * @LastEditors: Yongchao Wang
 * @LastEditTime: 2020-12-05 14:35:21
 */
import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import '../model/category_goods.dart';
import '../service/service_method.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:fluttertoast/fluttertoast.dart';

class CategoryGoodsListProvide with ChangeNotifier, DiagnosticableTreeMixin {
  List<CategoryGoodsModel> _goodsList = [];
  int _selectedIndex = 0;
  var _data = {"page": 1, "categorySubId": ''};
  requestGoodsList(
      {String categoryId,
      String categorySubId,
      int page,
      bool add = false,
      EasyRefreshController controller}) async {
    if (categoryId != null) {
      _data['categoryId'] = categoryId;
    }
    if (categorySubId != null) {
      _data['categorySubId'] = categorySubId;
    }
    if (page != null) {
      _data['page'] = page;
    }
    if (add) {
      _data['page'] = (_data['page'] as int) + 1;
    }

    var value = await request('getMallGoods', 'post', _data);
    var response = jsonDecode(value.toString());
    CategoryGoodsListModel goodsListModel =
        CategoryGoodsListModel.fromJson(response);
    if (controller != null) {
      if (_data['page'] == 1) {
        _goodsList = goodsListModel.data == null ? [] : goodsListModel.data;
        controller.finishRefresh();
        if (goodsListModel.data.length < 20) {
          controller.finishLoad(noMore: true);
        }
      }
      if ((_data['page'] as int) > 1) {
        List tempList = goodsListModel.data == null ? [] : goodsListModel.data;
        _goodsList.addAll(tempList as List<CategoryGoodsModel>);

        if (goodsListModel.data == null || goodsListModel.data.length < 20) {
          controller.finishLoad(success: true, noMore: true);
          Fluttertoast.showToast(
              msg: "没有更多了",
              toastLength: Toast.LENGTH_SHORT,
              gravity: ToastGravity.CENTER,
              timeInSecForIosWeb: 1,
              backgroundColor: Colors.black,
              textColor: Colors.white,
              fontSize: 16.0);
        }
      } else {
        controller.finishLoad(success: true, noMore: false);
      }
    } else {
      _goodsList = goodsListModel.data == null ? [] : goodsListModel.data;
    }

    notifyListeners();
  }

  setSelectedIndex(index) {
    _selectedIndex = index;
    notifyListeners();
  }

  List get goodsList => _goodsList;
  int get selectedIndex => _selectedIndex;

  /// Makes `Counter` readable inside the devtools by listing all of its properties
  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
  }
}
